<?php

namespace App\Service\Third;

use App\Constants\ErrorCode;
use App\Helpers\PayUtil;
use App\Helpers\DougongPayUtil;
use App\Helpers\RedisUtil;
use App\Model\PaycallbackLog;
use App\Model\PayOrder;
use App\Model\Service\PaycallbackService;

/**
 * 新支付回调
 */
class DougongPayCallbackService extends PayBaseService
{

    public function handle()
    {
	$callbackArray = $this->request->all();


        $resp_data = json_decode($callbackArray['resp_data']);
        log_info(__CLASS__ . "==" . json_encode($callbackArray));

        //订单号
        $outTradeNo = $resp_data->req_seq_id;

        //回调如果支付不成功不改变状态值
        if ($resp_data->trans_stat != 'S') {
            log_info(__CLASS__ . "==STATUSERR==" . $resp_data->trans_stat);
            return ['result' => 0];
        }
        //记录回调日志
        $record = PayOrder::getByOutTradeNo($outTradeNo);
        if (!$record) return ['result' => 0];
        PaycallbackLog::addRecord($record['channel'], $outTradeNo, $callbackArray['resp_data']);

        //处理订单
        $callbackArray['money'] = $resp_data->trans_amt;
        $payMoney = $this->parsePayMoney($callbackArray);
        $str = PaycallbackService::successCallback($outTradeNo, $payMoney, $record['channel']);
        log_info(__CLASS__ . "==Success=={$outTradeNo}");
        return ['result' => 1];
    }
   
    /**
     * 解析支付总金额（分）
     */
    protected function parsePayMoney($callbackArray = [])
    {
        return isset($callbackArray['money']) ? intval($callbackArray['money'] * 100) : 0;
    }

    // 计算签名
    protected function getSign($param){
        ksort($param);
        reset($param);
        $signstr = '';

        foreach($param as $k => $v){
            if($k != "sign" && $k != "sign_type" && $v!=''){
                $signstr .= $k.'='.$v.'&';
            }
        }
        $signstr = substr($signstr,0,-1);
        $signstr .= NewPayUtil::PAY_KEY;
        $sign = md5($signstr);
        return $sign;
    }
}
